#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static unsigned char myfilter(unsigned char sta)
{
#define FIILTER_DEPTH 3//滤波级数，必须1-32
#define MASK (0xffffffff >> (32-FIILTER_DEPTH))
	static unsigned int old_sta=0;
	old_sta= (old_sta<<1) | (sta&0x1);
	if((old_sta & MASK) == MASK)
		return 1;
	else
		return 0;
}

void filter_max8_edge2(uint8_t *filter, uint8_t lv, uint8_t in, uint8_t *out)
{
	const uint8_t mask_list[7] = {(0xff >> (8-2)), (0xff >> (8-3)), (0xff >> (8-4)),\
			(0xff >> (8-5)), (0xff >> (8-6)), (0xff >> (8-7)), (0xff >> (8-8))};
	uint8_t mask;			
	if(lv > 1 && lv <= 8) {
		mask = mask_list[lv-2];
		*filter= ((*filter) << 1) | (in&0x1);
		if( (*out && ((*filter | (~mask)) == (~mask))) ||\
				(*out == 0 && (((*filter) & mask) == mask)) ){
			*out = in;	
		}
	}else {
		*out = in;
	}
}

void test1(void) {
    int i = 0,sta;
	for(i = 0;  i< 100; i++) {
		if(i%10 == 0) {
			sta=0;
		}
		else {
			sta=1;
		}
		if(myfilter(sta)) {
			printf("err [%d]\n", i);
		}
	}
}

void test2(void) {
    uint8_t i = 0, sta, filter = 0, out = 0, last_out;
	for(i = 0;  i< 100; i++) {
		if(i%10 >= 5) {
			sta=0;
		}
		else {
			sta=1;
		}
        filter_max8_edge2(&filter, 4, sta, &out);
		if(out != last_out) {
			printf("err [%d]\n",i);
		}
        last_out = out;
	}
}

int main(int argc, char **argv)
{
	test2();
	
	return 0;
}